import { reactive, computed } from "vue";
import { defineStore } from "pinia";
import { loginApi } from "@/api/user.js"
export const useUserStore = defineStore("user", () => {
    const user = reactive({
        token: "",
        userinfo: JSON.parse(localStorage.getItem("permission")) || [],
        permission: JSON.parse(localStorage.getItem("permission")) || []
    });
    //获取用户信息 计算属性
    const getUser = computed(() => user);
    //actions 登录入口
    function login(data) {
        return new Promise(resolve => {
            loginApi(data).then(res => {
                if (res.code == 0) {
                    user.token = res.data.token
                    user.userinfo = res.data.userinfo
                    user.permission = res.data.permission
                    localStorage.setItem("permission", JSON.stringify(res.data.permission))
                    localStorage.setItem("userinfo", JSON.stringify(res.data.userinfo))
                }
                resolve(res)
            })
        })
    }
    function loginOut() {
        return new Promise(resolve => {
            user.token = ""
            user.userinfo = ""
            user.permission = []
            localStorage.removeItem("permission")
            localStorage.removeItem("userinfo")
            resolve()
        })
    }
    return { getUser, login, loginOut };
});
